package org.devocean.groupbuying.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.devocean.groupbuying.dao.ArticleDAO;
import org.devocean.groupbuying.domain.Article;
import org.springframework.stereotype.Repository;

@Repository
public class ArticleDAOImpl implements ArticleDAO {

	@PersistenceContext
	private EntityManager em;

	public long countArticles() {
		return em.createQuery("SELECT COUNT(a)  FROM Article a", Long.class)
				.getSingleResult();
	}

	public List<Article> findAllArticles() {
		return em
				.createQuery(
						"SELECT a  FROM Article a JOIN FETCH  a.articlesLocalization al",
						Article.class).getResultList();
	}

	public List<Article> findArticlesEntries(int firstResult, int maxResults) {
		return em
				.createQuery(
						"SELECT a  FROM Article a JOIN FETCH  a.articlesLocalization",
						Article.class).setFirstResult(firstResult)
				.setMaxResults(maxResults).getResultList();
	}

	public void deleteArticle(int id) {
		final Article article = em.find(Article.class, id);
		Article articleRemove = article;
		article.getArticlesLocalization().setArticles(null);
		if (article != null) 
				em.remove(articleRemove);
	}

	public Article findArticleById(Integer id) {
		return em.find(Article.class, id);
	}

	public List<Article> findArticlesByLang(String lang) {
		final Query query = em.createQuery(
				"select a from Article a where  a.lang=:lang", Article.class);
		query.setParameter("lang", lang);
		return query.getResultList();
	}

	public Article findArticleBylang(Integer LocalisationKey, String language) {
		final Query query = em
				.createQuery(
						"select a from Article a where a.articlesLocalization.articlesLocalizationID=:key and a.lang=:lang",
						Article.class);
		query.setParameter("key", LocalisationKey);
		query.setParameter("lang", language);
		Article article = (Article) query.getResultList().get(0);
		if (article == null) {
			final Query alternQuery = em
					.createQuery(
							"select a from Article a where a.articlesLocalization.articlesLocalizationID=:key ",
							Article.class);
			query.setParameter("key", LocalisationKey);
			article = (Article) alternQuery.getResultList().get(0);
		}

		return article;
	}

}
